/*
 *  xyos/trunk/src/homework/p3.c
 *
 *  Harry Wei <harrxiyou@gmail.com> (C) 2011
 */
#include "process_control.h"

static GStaticMutex p3_safe_mutex = G_STATIC_MUTEX_INIT;
static uint64_t main_counter = 0;
static uint64_t counter[MAX_THREAD];
static pthread_t pthread_id[MAX_THREAD];

static void *thread_work(gpointer data) 
{
	int thread_num = *(int *) data;
	g_message("thread num is %d", thread_num);
	pthread_id[thread_num] = pthread_self();
	while (1) {
		g_static_mutex_lock(&p3_safe_mutex);
		counter[thread_num] += 1;
		main_counter += 1;
		g_static_mutex_unlock(&p3_safe_mutex);
		sleep(1);
	}
}

int p3(int argc, char **argv)
{//TODO  ctrl + c unlock the mutex
	int i = 0;
	int rth = 0;
	char ch = 0;
	GThread *thread[MAX_THREAD];

	memset(pthread_id, 0, MAX_THREAD);
	memset(counter, 0, MAX_THREAD);
	g_thread_init(NULL);
	for(i = 0; i < MAX_THREAD; i++) {	
		//TODO why i can not just *see* all three threads running ??? ONE or TWO
		thread[i] = g_thread_create(thread_work, 
						(void *) &i,
						TRUE,
						NULL);
	}
	do {
		uint64_t sum = 0;
		g_static_mutex_lock(&p3_safe_mutex);
		for (i = 0; i < MAX_THREAD; i++) {
			sum += counter[i];
			g_message("%s -- couter[%d] is %llu", __func__, i, counter[i]);
		}
		g_message("%llu  /  %llu", main_counter, sum);
		g_static_mutex_unlock(&p3_safe_mutex);
		sleep(1);
	} while ('q' != (ch = getchar()));
#if 0
	for (i = 0; i < MAX_THREAD; i++) {
		g_thread_join(thread[i]);
	}
	g_thread_exit(NULL);
#endif
	return 0;
}
